package com.miukoo.aikao.admin.security;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.miukoo.aikao.admin.service.JwtUserRedisService;
import com.miukoo.aikao.core.pojos.SecurityUser;
import com.miukoo.aikao.core.utils.AppUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * 依据JTI自动授权
 * @Author miukoo<miukoo@126.com>
 * @Date 2020/11/22  
 * @Version 1.0
 */
@Component
public class JtiAuthenticationFilter extends GenericFilterBean {

    @Autowired
    JwtUserRedisService jwtUserRedisService;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        String uri = req.getRequestURI();
        System.out.println("=============="+uri);
        doAuthentication(req);
        chain.doFilter(request, response);
    }

    public void doAuthentication(HttpServletRequest request) throws JsonProcessingException {
        String jwtid = request.getHeader("token");
        if(StringUtils.isNotEmpty(jwtid)) {
            SecurityUser user = jwtUserRedisService.getUser(jwtid);
            if(user!=null) {
                List<SecurityGrantedAuthority> list = null;
                if (user.getAuthorities() != null) {
                    list = objectMapper.readValue(user.getAuthorities(), new TypeReference<List<SecurityGrantedAuthority>>() {
                    });
                }
                SecurityUserDto principal = new SecurityUserDto(user.getId(), user.getUserName(), "", list);
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null, list);
                AppUserUtils.setUser(user);
                SecurityContextHolder.getContext().setAuthentication(token);
            }
        }
    }

}